package com.qiwenshare.file.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiwenshare.file.domain.FileBean;
import com.qiwenshare.file.domain.UserFile;
import com.qiwenshare.file.mapper.FileMapper;
import com.qiwenshare.file.mapper.ImageMapper;
import com.qiwenshare.file.mapper.UserFileMapper;
import com.qiwenshare.file.util.FastJsonUtil;
import com.qiwenshare.file.util.FileUploadUtils;
import com.qiwenshare.ufop.util.UFOPUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import static com.qiwenshare.file.util.FileUploadUtils.checkFileExt;
import static com.qiwenshare.file.util.FileUploadUtils.propertyUtil;

@Slf4j
@Tag(name = "filetransferCopy", description = "该接口为文件传输接口，主要用来做文件的上传、下载和预览")
@RestController
@RequestMapping("/filetransferCopy")
public class FiletransferCopyController {

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private UserFileMapper userFileMapper;

    private static  String userFileIds="";//用户上传的文件名集合
    private  static  String  fileSuffixs="";//文件后缀名 集合

    private static String getProjectRootDirPath(){
        return propertyUtil.getProperty("file.root");
    }
    //4.文件夹逐个读取文件示例
    @RequestMapping(value="/uploadEveryFile",method={RequestMethod.POST})
    @Transactional
    public Map<String,Object> getEveryFile(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file") MultipartFile[] multipartFile) throws Exception {

         userFileIds="";
         fileSuffixs="";
        //必传
        String  id=request.getParameter("id");//商品记录的ID
        String  productNo=request.getParameter("productNo");//商品编号
        String  childFileType=request.getParameter("childFileType");
        String fileType="",insertNum="0";
        //文件类型 1:图片;2:视频
        if(childFileType.equals("1")||childFileType.equals("2")||childFileType.equals("3")||childFileType.equals("4")
                ||childFileType.equals("5"))
        {
            fileType="1";//1:参考图片;2:网红图;3:商品图;4:站外图;5:对色图;
        }
        else {
            fileType="2";//6:主图视频7:网红视频;8:广告视频9:品牌视频10:A+视频 11:3D动画
        }
        String userId=request.getParameter("userId");//上传操作用户

        //可选
        String  pictureColor=request.getParameter("pictureColor");
        //平台 1:亚马逊;2:TEMU;3:SHEIN;4:TK;5:沃尔玛;6:独立站
        String  platform=request.getParameter("platform");
        //图片分类 1:主副图;2:A+;3:关联图;4:SB广告图；5:SD广告图;6:POST图片;7:线稿图;8:标签图
        String  pictureType=request.getParameter("pictureType");
        //规格
        String  specifications=request.getParameter("specifications");
        //销售状态 0:在售;1:停售
        String  saleStatus=request.getParameter("saleStatus");
        //上传文件ID 文件系统返回
        String  userFileId="";
        ///////////////////////
        String flag="";//响应返回值
        // 指定文件夹路径
        String folderPath =request.getParameter("folderPath");// "D:\\test";

        System.out.println("上传文件个数:"+multipartFile.length);
        for (int i=0;i<multipartFile.length;i++) {
            //获取文件名
            String fileName = multipartFile[i].getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            String fileId = toString(new Date(), "yyMMdd") + System.currentTimeMillis();
            //获取文件路径
            String projectPath = "D://swq//release//static//";
            String filePath = "upload";
            filePath += "/" + toString(new Date(), "yyyyMMdd") + "/" + fileId + "." + ext;

            //指定本地文件夹存储图片
            File dir = new File(projectPath + filePath);
            if (!dir.getParentFile().exists()) {
                dir.getParentFile().mkdirs();
            }
            if (multipartFile[i] != null) {
                System.out.println(multipartFile[i]);
                MultipartFile imgFile =multipartFile[i];
                imgFile.transferTo(dir);
            }
        }

        /*
        // 创建文件夹对象
        File folder = new File(folderPath);
        // 检查文件夹是否存在
        if (folder.exists() && folder.isDirectory()) {
            // 获取文件夹中的所有文件
            File[] files = folder.listFiles();
            // 遍历文件数组
            for (File file : files) {
                // 检查是否为文件
                if (file.isFile()) {
                    System.out.println(file.getPath());
                    String fileSuffix = file.getPath().substring(file.getPath().lastIndexOf("."));

                    //获取文件路径
                    String projectPath ="D://swq//release//static//";
                    String filePath = getPath(fileSuffix,"");
                    File fileNew= new File(projectPath+filePath);

                    //如果目录不存在，则创建
                    if(!fileNew.getParentFile().exists()){
                        fileNew.getParentFile().mkdirs();
                    }
                    //保存文件
              //      file.transferTo(fileNew);





                    userFileId=uploadFileAdd(file.getPath(),fileSuffix);
                    if(userFileIds.equals("")) {
                        userFileIds = userFileId;
                        fileSuffixs=fileSuffix;
                    }
                    else {
                        userFileIds=userFileIds+","+userFileId;
                        fileSuffixs=fileSuffixs+","+fileSuffix;
                    }
                }
                else { ///如果还是文件夹
                    if(file.exists() && file.isDirectory())
                    {
                        xunHuan(file);
                    }
                }
            }

            String numArr []=userFileIds.split(",");
            System.out.println("上传文件个数:"+numArr.length);
            System.out.println("文件组合:"+userFileIds);
            System.out.println("后缀组合:"+fileSuffixs);

         *//*   if(!userFileIds.equals("")) {
                JSONObject jsobj1 = new JSONObject();
                jsobj1.put("id",id);
                jsobj1.put("productNo", productNo);
                jsobj1.put("fileType",fileType);
                jsobj1.put("childFileType",childFileType);
                jsobj1.put("pictureColor",pictureColor);
                jsobj1.put("platform",platform);
                jsobj1.put("pictureType",pictureType);
                jsobj1.put("specifications",specifications);
                jsobj1.put("saleStatus",saleStatus);
                jsobj1.put("userFileIds",userFileIds);
                jsobj1.put("fileSuffixs",fileSuffixs);
                jsobj1.put("userId",userId);
                String returnStr=post(jsobj1,"http://127.0.0.1:8081/upload/fileMore");
                Map<String, Object> map=json2Map(returnStr.toString());
                flag =map.get("flag").toString();
                insertNum=map.get("insertNum").toString();
            }*//*

        } else {
            System.out.println("文件夹不存在或不是一个文件夹。");
            //响应
            Map<String,Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
            jsonObject.put("flag",false);     //设置Json对象的属性
            jsonObject.put("msg","文件夹不存在或不是一个文件夹,上传数量为"+insertNum);
            return jsonObject;
        }

        if(flag.equals("true")) {//返回插入数据成功,给前端返回结果
            //响应
            Map<String,Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
            jsonObject.put("flag",true);     //设置Json对象的属性
            jsonObject.put("msg","已经成功批量上传"+insertNum+"文件.");
            return jsonObject;
        }
        else*/
        {
            //响应
            Map<String,Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
            jsonObject.put("flag",false);     //设置Json对象的属性
            jsonObject.put("msg","批量上传失败");
            return jsonObject;
        }
    }


    //递归调用
    public  void xunHuan(File folder) throws Exception {
        ////
        // 获取文件夹中的所有文件
        File[] files = folder.listFiles();
        // 遍历文件数组
        for (File file : files) {
            // 检查是否为文件
            if (file.isFile()) {
                System.out.println(file.getPath());
                String fileSuffix = file.getPath().substring(file.getPath().lastIndexOf("."));

                String userFileId=uploadFileAdd(file.getPath(),fileSuffix);
                if(userFileIds.equals("")) {
                    userFileIds = userFileId;
                    fileSuffixs=fileSuffix;
                }
                else {
                    userFileIds=userFileIds+","+userFileId;
                    fileSuffixs=fileSuffixs+","+fileSuffix;
                }
            }
            else { ///如果还是文件夹
                if(file.exists() && file.isDirectory())
                {
                    xunHuan(file);
                }
            }
        }
        /////
    }

    ///4.1
    public static String post(JSONObject json,String url) {
        String result="";
        try {
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(url);
            post.setHeader("Content-Type", "appliction/json");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity s=new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "appliction/json"));
            post.setEntity(s);
            HttpResponse httpResponse=client.execute(post);
            InputStream in=httpResponse.getEntity().getContent();
            BufferedReader br=new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber=new StringBuilder();
            String line=null;
            while ((line=br.readLine())!=null) {
                strber.append(line+"\n");
            }
            in.close();
            result=strber.toString();
            if(httpResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
                result="服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }
        System.out.println("result=="+result);
        return result;
    }


    //4.2逐个插入
    public   String uploadFileAdd(String sourceFile,String fileSuffix) throws Exception {
        String fileId=toString(new Date(), "yyyyMMdd")+System.currentTimeMillis();
        String fileName=fileId+fileSuffix;
        long fileSize=0;

        String ext =fileName.substring(fileName.lastIndexOf(".")+1);
        //获取文件路径
        String projectPath ="D://swq//release//static//";
        String filePath = "upload";
        filePath+="/"+ toString(new Date(), "yyyyMMdd")+"/"+fileId+"."+ext;
        try {
            File file= new File(projectPath+filePath);
            //如果目录不存在，则创建
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }

            FileInputStream fis = null;
            FileOutputStream fos = null;
            String targetFile =projectPath+filePath;
            try
            {
                fis = new FileInputStream(sourceFile);
                fos = new FileOutputStream(targetFile);
                // 从源文件中读取数据
                int data;
                while ((data = fis.read()) != -1) {
                    // 将数据写入目标文件中
                    fos.write(data);
                }
                System.out.println("文件保存成功！");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            }

            File fileExist= new File(projectPath+filePath);
            if(fileExist.exists()) fileSize=fileExist.length();
            System.out.println("服务端文件名:"+fileName);
            System.out.println("服务端文件大小:"+fileSize);

            String userId="1";//管理员账号
            ///保存上传文件信息
            FileBean fileBean = new FileBean();
            fileBean.setCreateUserId(userId);
            fileBean.setFileId(fileId);
            fileBean.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            fileBean.setFileSize(fileSize);
            fileBean.setFileStatus(1);//1:生效
            fileBean.setFileUrl(filePath);
            fileBean.setStorageType(0);
            fileBean.setIdentifier(toString(new Date(), "yyyyMMdd")+System.currentTimeMillis());
            int num= fileMapper.insertRecord(fileBean);
            System.out.println("num数值:"+num);
            ///end-保存上传文件信息
            /////保存userFile
            UserFile userFile=new UserFile();
            userFile.setUserFileId(fileId);
            userFile.setCreateTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            userFile.setUploadTime(toString(new Date(), "yyyy-MM-dd hh:mm:ss"));
            userFile.setCreateUserId(userId);
            userFile.setDeleteFlag(0);
            userFile.setExtendName(ext);
            userFile.setFileId(fileId);
            userFile.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));
            userFile.setFilePath("/商品系统");
            userFile.setIsDir(0);
            userFile.setUserId(userId);
            userFileMapper.insert(userFile);
            /////END-保存userFile
            ///保存图片的宽度、高度
            try {
                if (UFOPUtils.isImageFile(ext)) {//是图片扩展名内的
                    File file1= new File(projectPath+filePath);
                    // 1.打开并读取文件
                    if (!file1.exists()) {// 检查文件是否存在
                        //响应信息 json字符串格式
                        Map<String,Object> responseMap = new HashMap<String,Object>();
                        responseMap.put("flag", false);
                        responseMap.put("msg", "文件不存在");
                        //生成响应的json字符串
                        String jsonResponse = JSONObject.toJSONString(responseMap);
                        System.out.println("jsonReponse:"+jsonResponse);
                    /*    ///返回给客户端的数据
                        final String output =jsonResponse;
                        response.setContentLength(output.length());
                        response.getOutputStream().write(output.getBytes());
                        response.getOutputStream().flush();
                        response.getOutputStream().close();
                        ////end-返回给客户端的数据*/
                    }
                    // 读取文件
                    Image src = ImageIO.read(file1);// 这一步对大图片来说如20M 非常耗内存约1G
                    // 2.计算压缩后的宽高
                    // like12 modified,20230419,优化 合并读文件 只读一次,解决2次读白耗内存的问题
                    int width = src.getWidth(null); // 得到源图宽
                    int height = src.getHeight(null); // 得到源图长
                    com.qiwenshare.file.domain.Image image = new com.qiwenshare.file.domain.Image();
                    image.setImageWidth(width);
                    image.setImageHeight(height);
                    image.setFileId(fileId);
                    imageMapper.insert(image);
                }
            } catch (Exception e) {
                System.out.println("生成图片缩略图失败！"+e.getMessage());
                return "0";
            }
            ///end-保存图片的宽度、高度
        } catch (Exception e) {
            return "0";
        }
        return  fileId;
    }

    ///4.3转换
    public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            JSONObject json = JSONObject.parseObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<Object> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = (JSONObject) it.next();
                        list.add(json2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        }else{
            return null;
        }
    }

    public static String toString(Date date, String pattern) {
        if(date == null) {
            return "";
        } else {
            if(pattern == null) {
                pattern = "yyyy-MM-dd";
            }

            String dateString = "";
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);

            try {
                dateString = sdf.format(date);
            } catch (Exception var5) {
                var5.printStackTrace();
            }

            return dateString;
        }
    }
    public String responseData(String path,int error,String message,HttpServletResponse response) throws IOException {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("url", path);
        map.put("error", error);
        map.put("message", message);
        response.getWriter().write(FastJsonUtil.obj2JsonString(map));
        return null;
    }
    private String getPath(HttpServletRequest request,String ext,String param){
        String filePath = "upload";
        if(param!=null && param.trim().length()>0){
            filePath+=param;
        } //else{
        //   filePath+= propertyUtil.getProperty("projectName");
        //  }
        filePath+="/"+ toString(new Date(), "yyyyMMdd")+"/"+System.currentTimeMillis()+"."+ext;
        return filePath;
    }

}
